package com.donger.boms.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.donger.boms.entity.Product;
import com.donger.boms.service.ProductBomService;
import com.donger.boms.service.ProductService;
import com.donger.boms.utils.Res;
import com.donger.boms.utils.Result;
import lombok.AllArgsConstructor;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;

@RestController
@RequestMapping("/product")
@AllArgsConstructor
public class ProductController {

    private final ProductService productService;
    private final ProductBomService productBomService;

    @GetMapping("/page")
    public Result page(Page<Product> page,Product product){
        return Res.ok(productService.pageList(page, product));
    }
    /**
     * 下载模板
     * @param response
     * @throws IOException
     */
    @GetMapping("/downloadTemplate")
    public void downloadModel(HttpServletResponse response) throws IOException {
        productService.exportExcel(response.getOutputStream());
        String fileName = "导入模板.xlsx";
        try {
            fileName = java.net.URLEncoder.encode(fileName, "utf-8");// IE11 浏览器
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        response.setContentType("application/force-download");
        response.addHeader("Content-Disposition", "attachment;fileName=" + fileName);
    }
    /**
     * 批量导入
     * @param file
     * @return
     */
    @PostMapping("/upload")
    public Result upload(@RequestParam("file") MultipartFile file){
        productService.upload(file);
        return Res.ok(true);
    }
}
